package com.hsck.order.kds.main.fragment.noodles.batch

import android.app.Activity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hsck.order.kds.R
import com.hsck.order.kds.base.isnoam.log.XFrame
import com.hsck.order.kds.base.isnoam.log.XLog
import com.hsck.order.kds.base.utils.calculateMinutesSinceOrder
import com.hsck.order.kds.databinding.BatchNoodleCuttingHeaderLayoutBinding
import com.hsck.order.kds.databinding.BatchNoodleCuttingItemLayoutBinding
import com.hsck.order.kds.main.dialog.SelectNumberDialog
import com.hsck.order.kds.main.dialog.SelectQuantityDialog
import com.hsck.order.kds.main.fragment.standard.bean.TestListBean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class BatchNoodleCuttingAdapter(val activity: Activity) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var list: MutableList<TestListBean> = arrayListOf()
    private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private val viewHolders = mutableListOf<ItemVH>()

    companion object {
        const val TYPE_ITEM = 0
        const val TYPE_HEADER = 1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == TYPE_ITEM) {
            val viewHolder = ItemVH(
                BatchNoodleCuttingItemLayoutBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false
                )
            )
            viewHolders.add(viewHolder)
            viewHolder
        } else {
            HeaderVH(
                BatchNoodleCuttingHeaderLayoutBinding.inflate(
                    LayoutInflater.from(parent.context), parent, false
                )
            )
        }
    }

    inner class HeaderVH(val binding: BatchNoodleCuttingHeaderLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bindHeaderData() {
            binding.bean = list[0]
            binding.tvAllCount.setOnClickListener {
                val totalSum = list.sumOf { it.number }
                val hasFalseSelected = list.any { !it.itemSelected }
                list.forEach {
                    if (hasFalseSelected) {
                        it.selectedNumber = it.number.toString()
                        it.itemSelected = true
                        list[0].totalSum = totalSum.toString()
                    } else {
                        it.selectedNumber = ""
                        list[0].totalSum = ""
                        it.itemSelected = false
                    }
                }
                onDishOperationListener.onDishOperationSelectedAction()
            }
        }
    }

    inner class ItemVH(val binding: BatchNoodleCuttingItemLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {
        private var updateJob: Job? = null
        fun bindData(position: Int) {
            val item = list[position]
            binding.bean = item
            binding.tvTime.text = calculateMinutesSinceOrder(item.time).toString()

            if (item.selectedNumber.isNotEmpty()) {
                binding.tvNumberOfDish.text = item.selectedNumber
                binding.tvNumberOfDish.setTextColor(XFrame.getColor(R.color.color_007AFF))
                binding.tvNumberOfDish.background =
                    XFrame.getDrawable(R.drawable.blue_select_number_bg_shape)
            } else {
                binding.tvNumberOfDish.text = ""
                binding.tvNumberOfDish.setTextColor(XFrame.getColor(R.color.color_666666))
                binding.tvNumberOfDish.background =
                    XFrame.getDrawable(R.drawable.gray_unselect_number_bg_shape)
            }
            //划菜数量弹窗点击实际
            binding.tvNumberOfDish.setOnClickListener {
                //需要判断数量，根据不同数量展示不同弹窗
                when (item.number) {
                    1 -> {
                        //请求划菜接口
                        if (item.itemSelected) {
                            selectItemBean(0, item, position)
                        } else {
                            selectItemBean(item.number, item, position)
                        }
                    }

                    2 -> {
                        //显示选择1/2弹窗
                        showQuantityDialog(item, position)
                    }

                    else -> {
                        //显示设置数量弹窗
                        showNumberDialog(item, position)
                    }
                }
            }
            //当前对象的全部选中
            binding.tvTotalCount.setOnClickListener {
                if (item.itemSelected) {
                    if (item.number == item.selectedNumber.toInt()) {
                        selectItemBean(0, item, position)
                    } else {
                        selectItemBean(item.number, item, position)
                    }
                } else {
                    selectItemBean(item.number, item, position)
                }
            }
            binding.tvNumber.text = "x${item.number}"

            startLaunch(item)
        }

        private fun showQuantityDialog(item: TestListBean, position: Int) {
            val selectQuantityDialog = SelectQuantityDialog(activity)
            selectQuantityDialog.show("测试数据")
            selectQuantityDialog.setSelectQuantityListener(object :
                SelectQuantityDialog.SelectQuantityListener {
                override fun onSelectQuantity(i: Int) {
                    XLog.i("选择的数量为：$i")
                    selectItemBean(i, item, position)
                }
            })
        }

        /**
         * 数量大于2，设置划菜数量弹窗
         */
        private fun showNumberDialog(item: TestListBean, position: Int) {
            val selectNumberDialog = SelectNumberDialog(activity)
            selectNumberDialog.show("测试数据", item.number.toString(), true)
            selectNumberDialog.setSelectNumberListener(object :
                SelectNumberDialog.SelectNumberListener {
                override fun onSelectNumber(i: Int) {
                    XLog.i("选择的数量为：$i")
                    selectItemBean(i, item, position)
                }
            })
        }

        /**
         * 当前对象的全选中与取消全选
         */
        private fun selectItemBean(i: Int, item: TestListBean, position: Int) {
            if (i == 0) {//取消选中
                item.selectedNumber = ""
                item.itemSelected = false
                item.remainingNumber = ""
                val totalSum = list.sumOf {
                    if (it.selectedNumber.isNotEmpty()) it.selectedNumber.toInt() else 0
                }
                list[0].totalSum =
                    if (totalSum != 0) totalSum.toString() else ""//totalSum只更新header中的数据
            } else {//选中
                item.selectedNumber = i.toString()
                item.itemSelected = true
                item.remainingNumber =
                    (item.number - (item.selectedNumber.toInt())).toString()//剩余数量
                //所有选中的数量
                val totalSum = list.sumOf {
                    if (it.selectedNumber.isNotEmpty()) it.selectedNumber.toInt() else 0
                }
                list[0].totalSum =
                    if (totalSum != 0) totalSum.toString() else ""//totalSum只更新header中的数据
            }
            onDishOperationListener.onDishOperationSelectedAction()
        }

        /**
         * 启动定时器
         */
        private fun startLaunch(item: TestListBean) {
            updateJob = coroutineScope.launch {
                while (isActive) {
                    val time = calculateMinutesSinceOrder(item.time)
                    if (time != -1) {
                        binding.tvTime.text = "$time'"
                        if (time <= 10) {
                            if (binding.constraintStatus.tag != "enchanting") {
                                binding.constraintStatus.background =
                                    XFrame.getDrawable(R.drawable.home_dish_item_zhengchang_bg_shape)
                                binding.constraintStatus.tag = "enchanting"
                            }
                        } else if (time in 11..19) {
                            if (binding.constraintStatus.tag != "ring") {
                                binding.constraintStatus.background =
                                    XFrame.getDrawable(R.drawable.home_dish_item_yujing_bg_shape)
                                binding.constraintStatus.tag = "ring"
                            }
                        } else {
                            if (binding.constraintStatus.tag != "chaos") {
                                binding.constraintStatus.background =
                                    XFrame.getDrawable(R.drawable.home_dish_item_chaoshi_bg_shape)
                                binding.constraintStatus.tag = "chaos"
                            }
                        }
                    } else {
                        binding.tvTime.text = "时间格式错误"
                    }
                    delay(1000)
                }
            }
        }

        fun stopUpdating() {
            updateJob?.cancel()
            updateJob = null
        }
    }

    fun stopAllUpdating() {
        for (holder in viewHolders) {
            holder.stopUpdating()
        }
    }

    fun getSelectedList(): List<TestListBean> {
        return list.filter { it.itemSelected }
    }

    fun toggleItemSelected() {
        val hasFalse = list.any { !it.itemSelected }
        for (item in list) {
            item.itemSelected = hasFalse
        }
        onDishOperationListener.onDishOperationSelectedAction()
    }

    fun setListData(newList: MutableList<TestListBean>, append: Boolean = false) {
        if (append) {
            val startPosition = list.size
            list.addAll(newList)
            notifyItemRangeInserted(startPosition, newList.size)
        } else {
            list.clear()
            list.addAll(newList)
            notifyDataSetChanged()
        }

    }


    fun addItemAfterId(newItem: TestListBean, targetId: String) {
        val targetIndex = list.indexOfFirst { it.id == targetId }
        if (targetIndex != -1) {
            list.add(targetIndex + 1, newItem)
            notifyItemInserted(targetIndex + 1)
        }
    }

    fun removeItemAfterId(targetId: String) {
        val targetIndex = list.indexOfFirst { it.id == targetId }
        if (targetIndex != -1 && targetIndex + 1 < list.size) {
            list.removeAt(targetIndex + 1)
            notifyItemRemoved(targetIndex + 1)
            if (targetIndex < list.size) {
                notifyItemRangeChanged(targetIndex, list.size - targetIndex)
            }
        }
    }

    fun removeItemAfterIndex(targetIndex: Int) {
        if (targetIndex + 1 < list.size) {
            list.removeAt(targetIndex + 1)
            notifyItemRemoved(targetIndex + 1)
            if (targetIndex < list.size) {
                notifyItemRangeChanged(targetIndex, list.size - targetIndex)
            }
        }
    }

    override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
        super.onViewRecycled(holder)
        if (holder is ItemVH) {
            holder.stopUpdating()
            viewHolders.remove(holder)
        }
    }


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is ItemVH -> {
                val actualPosition = position - 1
                holder.bindData(actualPosition)
            }

            is HeaderVH -> {
                holder.bindHeaderData()
            }
        }
    }

    override fun getItemCount(): Int {
        return list.size + 1
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) {
            TYPE_HEADER
        } else {
            TYPE_ITEM
        }
    }

    private lateinit var onDishOperationListener: DishOperationListener
    fun setDishOperationListener(onDishOperationListener: DishOperationListener) {
        this.onDishOperationListener = onDishOperationListener
    }

    interface DishOperationListener {
        fun onDishOperationSelectedAction()
    }
}